import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../components/login.vue'
import home from '../components/home.vue'
import welcome from '../components/welcome.vue'
import user from '../components/user/users.vue'
Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/login'
},
{
  path: '/login',
  component: login
},
{
  path: '/home',
  component: home,
  redirect: '/welcome',
  children: [{
    path: '/welcome',
    component: welcome
  }, {
    path: '/users',
    component: user
  }

  ]
}

]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // to 表示将要访问的路径
  // from 表示代表从哪一个路径跳转来的
  // next表示一个函数，表示放行，next()放行，next(‘/login’)强制跳转
  // 如果用户访问登陆页面，直接放行
  if (to.path === '/login') return next()
  // 从sessionStorage中获取保存的token值
  const tokenStr = window.sessionStorage.getItem('token')

  // 如果用户没有登陆，则跳转到登陆页面
  if (!tokenStr) {
    return next('/login')
  }
  next()
})

export default router
